import { defineConfig, loadEnv } from 'vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'
import path from 'path'
export default ({ mode }) => {
  const envConfig = loadEnv(mode, './mode')
  return defineConfig({
    base: './',
    envDir: './mode',
    plugins: [
      vue({
        include: [/\.vue$/, /\.md$/],
      }),
      VueSetupExtend(),
      legacy({
        targets: ['defaults', 'not IE 11'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
        renderLegacyChunks: true,
        modernPolyfills: ['es.promise.finally'],
        polyfills: [
          'es.symbol',
          'es.array.filter',
          'es.promise',
          'es.promise.finally',
          'es/map',
          'es/set',
          'es.array.for-each',
          'es.object.define-properties',
          'es.object.define-property',
          'es.object.get-own-property-descriptor',
          'es.object.get-own-property-descriptors',
          'es.object.keys',
          'es.object.to-string',
          'web.dom-collections.for-each',
          'esnext.global-this',
          'esnext.string.match-all',
        ],
      }),
    ],
    server: {
      host: '0.0.0.0',
      https: false, // 是否开启 https
      port: 3000,
      open: true,
      proxy: envConfig.VITE_APP_TARGET
        ? {
            '/ajax': {
              target: envConfig.VITE_APP_TARGET,
              changeOrigin: true,
              rewrite: (path) => path.replace(/^\/ajax/, '/ajax'),
            },
          }
        : {},
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    build: {
      target: 'es2015',
      // sourcemap: true,
      minify: 'minify',
      // minify: envConfig.VITE_APP_ENV === 'production' ? 'terser' : false,
      terserOptions: {
        compress: {
          // warnings: false,
          drop_console: true, //打包时删除console
          drop_debugger: true, //打包时删除 debugger
          pure_funcs: ['console.log'],
        },
        output: {
          comments: true, // 去掉注释内容
        },
      },
      rollupOptions: {
        output: {
          // assetFileNames: `assets/[name].[ext]`,
          manualChunks: {
            vue: ['vue'],
            axios: ['axios'],
          },
        },
      },
    },

  })
}
